#include "win_link.h"
#include "stdio.h"
#include "../../lv_drv_conf.h"


#if (LV_USE_FS_WIN32 == 1)

#include "../../remote/lv_app/lv_app.h"
#include <windows.h>
#include <stdio.h>
#include <process.h>

uint8_t this_mode = 1;

void buzz_di(void);
void win_link_handler(void);
void win_32_tx_calib(uint16_t *data);
void win_32_tx_mode(uint8_t mode);
void win_32_tx_u8(uint8_t fun, uint8_t data);
void win_32_tx_u8_2(uint8_t fun, uint8_t data, uint8_t data2);

hal_link_t win_link = {
	.buzz_di = buzz_di,
	.hal_link_handler = win_link_handler,
    .tx_calib_buff = win_32_tx_calib,
	.tx_mode = win_32_tx_mode,
	.tx_u8 = win_32_tx_u8,
	.tx_u8_2 = win_32_tx_u8_2
};

void buzz_di(void)
{
	printf("buzz\n");
}

void win_32_tx_calib(uint16_t *data)
{
    printf("win_32_tx_calib ta data\n");
}

void win_32_tx_mode(uint8_t mode)
{
    printf("tx mode:%d\n", mode);
	this_mode = mode;
}

void win_32_tx_u8(uint8_t fun, uint8_t data)
{
    printf("tx u8 fun:%x  data:%d\n", fun, data);
}

void win_32_tx_u8_2(uint8_t fun, uint8_t data, uint8_t data2)
{
    printf("tx u8 fun:%x  data1:%d  data2:%d\n", fun, data, data2);
}

HANDLE lvgl_mutex;
HANDLE thread_driver, thread_lvgl;

// 定义一个线程函数，打印参数值
void driver_fun(void * arg)
{
	uint8_t thr = 0;
	
    while (1)
    {
        uint16_t adc_buff[] = {
            rand() % 4096,
            rand() % 4096,
            rand() % 4096,
            rand() % 4096,
        };

		if (++thr > 100) {
			thr = 0;
		}

		WaitForSingleObject(lvgl_mutex, INFINITE);//等待互斥量

        app_ch_calib_set_adc(adc_buff);
		
		set_show_mode(this_mode);

		uint8_t adc[] = {
			thr,
			thr,
			thr,
			thr,
			thr,
	
			thr,
			thr,
			thr,
			thr,
			thr,
		};

		uint8_t flag[] = {
			0,
			1,
			0,
			1,
			0,
			0,
			1,
			0,
			1,
			0,
		};

		set_remote_info(adc);
		set_remote_info_for_ch_set(adc, flag);

		ReleaseMutex(lvgl_mutex);

        Sleep(200);
    }
}

void lvgl_fun(void * arg)
{
    while(1) {
        WaitForSingleObject(lvgl_mutex, INFINITE);//等待互斥量
        lv_task_handler();
		ReleaseMutex(lvgl_mutex);
        Sleep(5); /* sleep for 10 ms */
    }
}


void win_link_handler(void)
{
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}

static uint8_t buff[32];

void win_link_init(void)
{

	// 线程id变量
	DWORD dwThreadId, dwThreadId1;

	lvgl_mutex = CreateMutex(NULL, FALSE, NULL);

	/* 创建线程 */
	thread_driver = (HANDLE)_beginthread(driver_fun, 0, NULL);//线程1
	thread_lvgl   = (HANDLE)_beginthread(lvgl_fun, 0, NULL);//线程2

	set_channel_user_ch_p(buff);
}

#endif
